<?php

namespace app\api\controller;

use addons\shopro\service\user\UserAuth;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\data\Page;
use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\order\OrderItem;
use app\common\controller\Api;
use app\common\model\GBillModel;
use app\common\model\ScorecModel;
use app\common\model\UserRepurchase;
use app\common\model\UserSGold;
use app\common\model\UserTaskRegister;
use think\Db;
use think\Exception;

class Task extends Api
{

    protected $noNeedLogin = ['taskFenFaGongXiang','taskGongXianFenYong','agentMoneyTask','taskUserRepurchase','taskUserRegister','userOrderRegister'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['taskFenFaGongXiang','taskGongXianFenYong','agentMoneyTask','taskUserRepurchase','taskUserRegister','userOrderRegister'];



    public function taskFenFaGongXiang(){
        $userOneInfo = (new \app\common\model\User())
            ->where('is_r_data_price',0)
            ->where('point_uid','>',0)
            ->where('u_level','>',0)
            ->find();




        if($userOneInfo){

            $goodsInfo = [];
            //查询商品的贡献值信息,并且根据点位和推荐进行见点和分享
            if($userOneInfo['u_level'] == 1){
                $goodsInfo = [
                    'gongxian'=>1,
                    'jifen'=>720
                ];
            }


            if($userOneInfo['u_level'] == 2){
                $goodsInfo = [
                    'gongxian'=>15,
                    'jifen'=>54000
                ];
            }



            if(empty($goodsInfo)){
                return;
            }
            //返还贡献值

            Db::startTrans();
            try {
                $userSpreadInfo = (new \app\common\model\User())->where('id',$userOneInfo['id'])->find();

                //把自己等级调整成赠送的
                if($goodsInfo['gongxian'] > 0){
                    //赠送一个积分给购买人
                    (new GBillModel())->gongxianU($goodsInfo['gongxian'],$userOneInfo['id'],'商品赠送贡献值');
                    //点位用户
                    $user_point_uid = $userSpreadInfo['point_uid'];
                    //见点奖=>根据point_uid来
                    for ($i=0;$i<10;$i++){
                        $user_point_uInfo = (new \app\common\model\User())->where('id',$user_point_uid)->find();

                        if($i == 0){
                            $user_point_uid = $user_point_uInfo['point_uid'];
                            continue;
                        }

                        if($user_point_uid == 0){
                            break;
                        }
                        if($user_point_uInfo['u_level'] == 1 && $i<5){
                            (new GBillModel())->gongxianU(1,$user_point_uid,'赠送贡献值(见点奖)');
                        }
                        //代理全程见点
                        if($user_point_uInfo['u_level'] == 2){
                            (new GBillModel())->gongxianU(1,$user_point_uid,'赠送贡献值(见点奖)');
                        }
                        $user_point_uid = $user_point_uInfo['point_uid'];
                    }

                    //并且给推荐的人对应数量
                    if($userSpreadInfo['parent_user_id'] != 0){
                        //给贡献值
                        (new GBillModel())->gongxianU($goodsInfo['gongxian'],$userSpreadInfo['parent_user_id'],'赠送贡献值(推荐奖)');
                        //给积分

                    }
                }

                if($goodsInfo['jifen'] > 0){
                    (new ScorecModel())->scorecU($goodsInfo['jifen'],$userOneInfo['id'],'商品赠送积分');
                    if($userSpreadInfo['parent_user_id'] != 0) {
                        if ($userSpreadInfo['u_level'] == 1) {
                            (new ScorecModel())->scorecU(180, $userSpreadInfo['parent_user_id'], '奖励积分(推荐客户)');
                        }

                        if ($userSpreadInfo['u_level'] == 2) {
                            (new ScorecModel())->scorecU(1800, $userSpreadInfo['parent_user_id'], '奖励积分(推荐VIP)');
                        }
                    }
                }

                (new \app\common\model\User())->where('id',$userOneInfo['id'])->update([
                    'is_r_data_price'=>1
                ]);
                Db::commit();
            }catch (Exception $exception){
                var_dump($exception->getMessage());
                Db::rollback();
            }
        }
        echo '123213';exit;
    }


    public function agentMoneyTask()
    {

        $userOneInfo = (new \app\common\model\User())
            ->where('is_a_data_price',0)
            ->where('is_r_data_price',1)
            ->find()->toArray();

        if(!$userOneInfo){
            return;
        }



        if($userOneInfo['point_uid'] == 0){
            (new \app\common\model\User())->where('id',$userOneInfo['id'])->update([
                'is_a_data_price'=>1
            ]);
            return;
        }

        $money = 360;
        if($userOneInfo['u_level'] == 2){
            $money = 3600;
        }




        //根据节点找人
        $arr = [
            'area_agent'=>[],
            'city_agent'=>[],
            'province_agent'=>[],
            'all_agent'=>[]
        ];
        $levelArr = [
            'normal'=>0,
            'area_agent'=>1,
            'city_agent'=>2,
            'province_agent'=>3,
            'all_agent'=>4
        ];
        $pointUid = $userOneInfo['point_uid'];
        $minLevel = 1;
        while(true){
            if($pointUid == 0){
                break;
            }
            $poInfo = (new \app\common\model\User())->where('id',$pointUid)->find()->toArray();

            if($levelArr[$poInfo['agent_level']] < $minLevel){
                $pointUid = $poInfo['point_uid'];
                continue;
            }
            $minLevel = $levelArr[$poInfo['agent_level']];
            $arr[$poInfo['agent_level']][] = $pointUid;

            $pointUid = $poInfo['point_uid'];
        }


        Db::startTrans();
        try {
            $noe_money = 0;

            if(!empty($arr['area_agent'])){
                $noe_money = bcmul($money,0.05,2);
                $u_money_i = bcdiv($noe_money,count($arr['area_agent']),2);

                foreach ($arr['area_agent'] as $value){
                    $this->gangen($u_money_i,$value);
                    //奖励佣金
                    WalletService::change($value, 'commission', $u_money_i, 'sys_money_u', [], '区级代理奖励');

                    //释放同比的积分
                    (new ScorecModel())->scorecU(-($u_money_i),$value,'积分释放余额(区级代理)');
                }


            }

            if(!empty($arr['city_agent'])){
                $ImIbnet = bcsub(bcmul($money,0.1,2),$noe_money,2);
                $noe_money += $ImIbnet;
                $u_money_i = bcdiv($ImIbnet,count($arr['city_agent']),2);

                foreach ($arr['city_agent'] as $value){
                    $this->gangen($u_money_i,$value);

                    //奖励佣金
                    WalletService::change($value, 'commission', $u_money_i, 'sys_money_u', [], '市级代理奖励');
                    //释放同比的积分
                    (new ScorecModel())->scorecU(-($u_money_i),$value,'积分释放余额(市级代理)');
                }


            }

            if(!empty($arr['province_agent'])){
                $ImIbnet = bcsub(bcmul($money,0.15,2),$noe_money,2);
                $noe_money += $ImIbnet;
                $u_money_i = bcdiv($ImIbnet,count($arr['province_agent']),2);

                foreach ($arr['province_agent'] as $value){
                    $this->gangen($u_money_i,$value);

                    //奖励佣金
                    WalletService::change($value, 'commission', $u_money_i, 'sys_money_u', [], '省级代理奖励');
                    //释放同比的积分
                    (new ScorecModel())->scorecU(-($u_money_i),$value,'积分释放余额(省级代理)');
                }


            }


            //总代理
            if(!empty($arr['all_agent'])){
                $ImIbnet = bcsub(bcmul($money,0.2,2),$noe_money,2);
                $u_money_i = bcdiv($ImIbnet,count($arr['all_agent']),2);

                foreach ($arr['all_agent'] as $value){
                    $this->gangen($u_money_i,$value);

                    //奖励佣金
                    WalletService::change($value, 'commission', $u_money_i, 'sys_money_u', [], '总代理奖励');
                    //释放同比的积分
                    (new ScorecModel())->scorecU(-($u_money_i),$value,'积分释放余额(总代理)');
                }


            }



            (new \app\common\model\User())->where('id',$userOneInfo['id'])->update([
                'is_a_data_price'=>1
            ]);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
        }
    }

    public function gangen($money = 0,$user_id = 0)
    {
        $moneyItem = bcdiv($money,5,2);
        //20%循环上5层
        $userInfo = (new \app\common\model\User())->where('id',$user_id)->find();
        $user_spread_id = $userInfo['parent_user_id'];
        for ($i= 0;$i<=4;$i++){
            if($user_spread_id == 0){
                break;
            }
            $user_spread_info = (new \app\common\model\User())->where('id',$user_spread_id)->find();
            //
            if($user_spread_info['u_level'] != 2){
                $user_spread_id = $user_spread_info['parent_user_id'];
                continue;
            }
            $userCount = (new \app\common\model\User())->where('parent_user_id',$user_spread_id)
                ->where('u_level',2)
                ->count();
            if($userCount < 2){
                $user_spread_id = $user_spread_info['parent_user_id'];
                continue;
            }
            WalletService::change($user_spread_info['id'], 'commission', $moneyItem, 'sys_money_u', [], '感恩奖奖励');

            //释放同比的积分
            (new ScorecModel())->scorecU(-($moneyItem),$user_spread_info['id'],'积分释放余额(感恩奖)');

            $user_spread_id = $user_spread_info['parent_user_id'];


        }

    }


    public function taskGongXianFenYong(){
        $itemGongXian = ShoproConfig::getConfigField('shop.basic.gongxian',false);

        if($itemGongXian > 0.01){
            $users = (new \app\common\model\User())->where('scoreg','>',0)->select();
            Db::startTrans();

            try {
                foreach ($users as $value){
                    $u_money_i = bcmul($value['scoreg'],$itemGongXian,2);
                    $moneyItem = bcdiv($u_money_i,3,2);
                    if($u_money_i > $value['scorec']){
                        continue;
                    }
                    //各种奖励
                    WalletService::change($value['id'], 'commission', $moneyItem, 'sys_money_u', [], '贡献值奖励佣金');
                    (new UserSGold())->gGoldU($moneyItem,$value['id'],'贡献值奖励购物券');
                    (new UserRepurchase())->repurchaseU($moneyItem,$value['id'],'贡献值奖励复购金');


                    //释放同比的积分
                    (new ScorecModel())->scorecU(-($u_money_i),$value['id'],'积分释放余额');

                    //分成3等份


                }
                (new OrderItem())->where('money_status',0)->update([
                    'money_status'=>1
                ]);
                Db::commit();
            }catch (Exception $exception){
                var_dump($exception->getMessage().$exception->getLine());
                Db::rollback();
            }
        }
    }


    /**
     * @desc 根据用户复购金
     * @return void
     */
    public function taskUserRepurchase()
    {
        //获取第一个复购金用户
        $userOneFind = (new \app\common\model\User())
            ->where('repurchase','>=',3600)
            ->find();
        if(!$userOneFind){
            return;
        }

        //扣除复购金并且创建需要创建账号的订单
        Db::startTrans();
        try {
            (new UserRepurchase())->repurchaseU(-(3600),$userOneFind['id'],'扣除复购金生成账号');
            //生成订单
            (new UserTaskRegister())->save([
                'user_id'=>$userOneFind['id'],
                'status'=>0
            ]);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
        }
    }


    public function taskUserRegister()
    {
        $uRegister = (new UserTaskRegister())->where('status',0)->find();
        $prefixes = array('130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '153', '155', '156', '157', '158', '159', '165', '170', '171', '172', '173', '175', '176', '177', '178', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '198', '199');
        $prefix = $prefixes[array_rand($prefixes)];
        $number = $prefix . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT). str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);

        //创建用户账号密码为123456，账号为1939334
        $userAuth = new UserAuth();
        $auth = $userAuth->register([
            'mobile'=>$number,
            'password'=>'123456a',
            'parent_user_id'=>$uRegister['user_id'],
            'point_uid'=>$uRegister['user_id'],
            'pp_user_id'=>$uRegister['user_id']
        ]);
        $user = $auth->getUser();
        (new UserTaskRegister())->where('id',$uRegister['id'])->update([
            'status'=>1,
            'new_user_id'=>$user->id
        ]);


    }



    public function userOrderRegister(){
        $userOrderData = (new UserTaskRegister())->where('status',1)->find();
        //直接变更等级等待返费即可
        Db::startTrans();
        try {

            (new \app\common\model\User())->where('id',$userOrderData['new_user_id'])->update([
                'u_level'=>2
            ]);

            (new UserTaskRegister())->where('id',$userOrderData['id'])->update([
                'status'=>2
            ]);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
        }
    }




}